package com.sam.im.heiqun.uis.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.FriendAdpter;
import com.sam.im.heiqun.uis.widgets.sidebar.CharacterParserUtil;
import com.sam.im.heiqun.uis.widgets.sidebar.CountryComparator;
import com.sam.im.heiqun.uis.widgets.sidebar.CountrySortModel;
import com.sam.im.heiqun.uis.widgets.sidebar.GetCountryNameSort;
import com.sam.im.heiqun.uis.widgets.sidebar.SideBar;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.DividerItemDecorationUtils;
import com.yuyh.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangguodong on 2017/1/16.
 */
public class SelecteLocalFriendActivity extends BaseSwipeBackActivity implements FriendAdpter.FriendListClickListener, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.list_friend)
    RecyclerView list_friend;
    @BindView(R.id.friend_dialog)
    TextView friend_dialog;
    @BindView(R.id.friend_sidebar)
    SideBar friend_sidebar;
    @BindView(R.id.ok)
    TextView ok;
    @BindView(R.id.search_edit)
    EditText search_edit;
    @BindView(R.id.swipe_refresh_widget)
    SwipeRefreshLayout swipeRefreshWidget;
    @BindView(R.id.selector_group)
    TextView selectorGroup;
    @BindView(R.id.relative_noresult)
    LinearLayout relative_noresult;

    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.There_are_no_local_friends_id)
    TextView There_are_no_local_friends_tx;
    private int lastVisibleItem = 0;
    private LinearLayoutManager mLayoutManager;

    private List<ImFriendEntivity> mBFriends;
    PGService mPgService;
    String uid = "";

    private List<CountrySortModel> mFriends;
    private CountryComparator pinyinComparator;
    /**
     * 获取字符串缩写
     */
    private CharacterParserUtil characterParserUtil;
    /**
     * 获取首字母
     */
    private GetCountryNameSort countryChangeUtil;
    private FriendAdpter mAdapter;
    private List<ImFriendEntivity> mFriendEntivities = new ArrayList<>();
    private int intenttag;
    private ImMessage imMessage;
    private String tagstring;
    private ImMessage colactionmsg;
    String str;
    @Override
    protected String getTitleText() {
        return getString(R.string.searchmyfriend);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
//        ok.setVisibility(View.VISIBLE);
        if (!EventBus.getDefault().isRegistered(this)) {
//            EventBus.getDefault().register(this);//订阅
        }
        mPgService = PGService.getInstance();
        mFriendEntivities = (List<ImFriendEntivity>) getIntent().getSerializableExtra("mFriendEntivities");
        search_edit.setOnKeyListener(onKeyListener);
        search_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isEmpty(s.toString().trim())) {
                    mBFriends = ToolsUtils.getWFriendsInfo();
                    initData();
                }
            }
        });
        intenttag = getIntent().getIntExtra("tag", 0);
        tagstring = getIntent().getStringExtra("tags");
        imMessage = (ImMessage) getIntent().getSerializableExtra("msg");
        colactionmsg = (ImMessage) getIntent().getSerializableExtra("imessage");
        if (intenttag != 0) {
            selectorGroup.setVisibility(View.VISIBLE);
        }
        initView();

    }

    private View.OnKeyListener onKeyListener = new View.OnKeyListener() {//软键盘监听
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER
                    && event.getAction() == KeyEvent.ACTION_DOWN) {
               str = search_edit.getText().toString().trim();
                if (null != str && !"".equals(str.toString())) {
                    mBFriends = new ArrayList<>();
                    List<ImFriendEntivity> mBFriendsm = ToolsUtils.getWFriendsInfo();//拿到本地好友列表
//                    List<ImFriendEntivity> imFriendEntivities = ImFriendEntivity.find(ImFriendEntivity.class, "currentid = ? and is_black=? and mobile like ? or nick_name like ? or name like ? or remark like ?", new String[]{ToolsUtils.getMyUserId() + "", "0",str,str,str,str});
//                    if (null != imFriendEntivities && imFriendEntivities.size() > 0) {
//                        mBFriends.addAll(imFriendEntivities);
                    if (null != mBFriendsm && mBFriendsm.size() > 0) {
//                        mBFriends.addAll(imFriendEntivities);
                        for (int i = 0; i < mBFriendsm.size(); i++) {
                            if (mBFriendsm.get(i).getMobile() != null && mBFriendsm.get(i).getMobile().contains(str)) {
                                mBFriends.add(mBFriendsm.get(i));
                                break;
                            }
                            if (mBFriendsm.get(i).getRemark() != null && mBFriendsm.get(i).getRemark().contains(str)) {
                                mBFriends.add(mBFriendsm.get(i));
                                break;
                            }
                            if (mBFriendsm.get(i).getName() != null && mBFriendsm.get(i).getName().contains(str)) {
                                mBFriends.add(mBFriendsm.get(i));
                                break;
                            }
                            if (mBFriendsm.get(i).getNickName() != null && mBFriendsm.get(i).getNickName().contains(str)) {
                                mBFriends.add(mBFriendsm.get(i));
                                break;
                            }
                            if (mBFriendsm.get(i).getId() != null && String.valueOf(mBFriendsm.get(i).getId()).contains(str)) {
                                mBFriends.add(mBFriendsm.get(i));
                                break;
                            }
                            if (mBFriendsm.get(i).getMobile() != null && mBFriendsm.get(i).getMobile().contains(str)) {
                                mBFriends.add(mBFriendsm.get(i));
                                break;
                            }
                        }
                        initData();

                    } else {
                        ToolsUtils.showToast(SelecteLocalFriendActivity.this, getResources().getString(R.string.no_friend));
                    }

                }
                return true;
            }
            return false;
        }
    };

    @Override
    public int getContentViewId() {
        return R.layout.activity_selecte_groupfriend;
    }

    private void initData() {
        mFriends = new ArrayList<>();
        for (int i = 0; i < mBFriends.size(); i++) {
            if (null == mFriendEntivities || mFriendEntivities.size() == 0) {
                mFriends.add(ToolsUtils.changeFriendEntvity(mBFriends.get(i), characterParserUtil, countryChangeUtil));
            }else {
                boolean isZai = false;
                for (int j = 0; j < mFriendEntivities.size(); j++) {
                    if ((mFriendEntivities.get(j).getId()).equals(mBFriends.get(i).getId())) {
                        isZai = true;
                        break;
                    }
                }
                if (!isZai) {
                    mFriends.add(ToolsUtils.changeFriendEntvity(mBFriends.get(i), characterParserUtil, countryChangeUtil));
                }

            }

        }
        Collections.sort(mFriends, pinyinComparator);//根据首字母进行排序
        mAdapter.refresh(mFriends);
        if (mBFriends.size()==0){
            relative_noresult.setVisibility(View.VISIBLE);
            //not_inquired.setText("本地未查询到，网络搜索");
            There_are_no_local_friends_tx.setText("本地未查询到，网络查找");
            tv_content.setVisibility(View.VISIBLE);
            tv_content.setText(str);
            tv_content.setVisibility(View.VISIBLE);
        }else {
            relative_noresult.setVisibility(View.GONE);
            tv_content.setVisibility(View.GONE);
            tv_content.setVisibility(View.GONE);
        }
    }

    private void initView() {
        /** 右侧字母栏*/
        friend_sidebar.setTextView(friend_dialog);
        friend_sidebar.setVisibility(View.GONE);
        pinyinComparator = new CountryComparator();
        countryChangeUtil = new GetCountryNameSort();
        characterParserUtil = new CharacterParserUtil();
        // 右侧sideBar监听
        friend_sidebar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = mAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    //这个设置的方式不是很准确流畅
                    list_friend.getLayoutManager().scrollToPosition(position);
                }
            }
        });
        /** 右侧字母栏 */

        list_friend.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        mFriends = new ArrayList<>();
        mAdapter = new FriendAdpter(getApplicationContext(), mFriends);
        mAdapter.setItemClickListener(this);
        mAdapter.setHintHeadview(true);
        list_friend.setAdapter(mAdapter);
        list_friend.addItemDecoration(new DividerItemDecorationUtils(getApplicationContext(), LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.black_divider)));
        swipeRefreshWidget.setOnRefreshListener(this);

        // 这句话是为了，第一次进入页面的时候显示加载进度条
        swipeRefreshWidget.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));

        mBFriends = ToolsUtils.getWFriendsInfo();
        initData();

        // 将联系人进行排序，按照A~Z的顺序
//        Collections.sort(mFriends, pinyinComparator);
    }

    @Override
    public void onAgreeNewFriendClick(View view, int position) {
        Bundle bundle = new Bundle();
        bundle.putLong("id", mFriends.get(position - 1).getId());
        bundle.putInt("type", 1);
        if (intenttag == 11) {
            setResult(ChatActivity.REQUST_SENDTOFRIEND);//关闭现有聊天窗口
            bundle.putLong("destid", mFriends.get(position - 1).getId());
            bundle.putSerializable("msg", imMessage);
            startActivity(ChatActivity.class, bundle);
            finish();
        } else if (null != tagstring && !"".equals(tagstring) && tagstring.equals("@")) {
            Intent putintent = new Intent();
            putintent.putExtra("friendname", mFriends.get(position - 1).getNickName());//昵称
            putintent.putExtra("friendid", mFriends.get(position - 1).getId());
            setResult(ChatGroupActivity.AITE_FRIENDS, putintent);//关闭现有聊天窗口
            finish();
       /* }else if (colactionmsg!=null){
            bundle.putLong("destid", mFriends.get(position-1).getId());
            bundle.putSerializable("msg", colactionmsg);
            startActivity(ChatActivity.class, bundle);
            finish();*/
        } else if ("12".equals(tagstring)) {//名片选择
            Intent intent = new Intent();
            intent.putExtra("friendname", mFriends.get(position - 1).getNickName());//昵称
            intent.putExtra("friendid", mFriends.get(position - 1).getId()+"");
            intent.putExtra("imId", mFriends.get(position - 1).getIMNo());
            intent.putExtra("headurl", mFriends.get(position - 1).getHeadUrl());
            setResult(10, intent);
            finish();
        } else {
            startActivity(FriendDetailActivity.class, bundle);
        }
    }

    @OnClick({R.id.ok, R.id.pre_v_back, R.id.selector_group,R.id.relative_noresult})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.relative_noresult:
                Intent intent1=new Intent();
                intent1.putExtra("str",str);
                intent1.setClass(this, SeachFriendsActivity.class);
                startActivity(intent1);

                /*Intent intent1 = new Intent();
                Bundle bundle1 = new Bundle();
                bundle1.putSerializable("str", str);
                startActivity(SeachFriendsActivity.class, bundle1);*/
                break;

            case R.id.pre_v_back:
                scrollToFinishActivity();
                break;
            case R.id.ok:
                if (null != mFriends && mFriends.size() > 0) {
                    for (int i = 0; i < mFriends.size(); i++) {
                        if (mFriends.get(i).isSelecte) {
                            uid = mFriends.get(i).getId() + ",";
                        }
                    }
                }
                if (uid.length() > 0 && uid.endsWith(",")) {
                    uid = uid.substring(0, uid.length() - 1);
                }
//                Intent intent = new Intent();
//                intent.putExtra("uids",uid);
//                setResult(1,intent);
//                scrollToFinishActivity();
                break;
            case R.id.selector_group:
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("msg", imMessage);
                startActivity(ChoseGroupActivity.class, bundle);
                break;
        }
    }

    @Override
    public void onRefresh() {
        swipeRefreshWidget.setRefreshing(false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onEventMainThread(String event) {
        switch (event) {
            case "关闭":
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
//        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
